from rest_framework import status
from rest_framework.generics import GenericAPIView, UpdateAPIView
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet, ModelViewSet, mixins

from company.models import Vehicle, VehicleCompanyTerminal
from location.models import Location, VehicleStatus
from location.serializers import (VehicleAddressSerializer,
                                  VehicleLocationDetailSerializer,
                                  VehicleStatusListSerializer,
                                  VehicleStatusUpdateSerializer)


class VehicleLocationDetailViewSet(mixins.RetrieveModelMixin,
                                   GenericViewSet):
    '''
    # 轨迹查询
        * vehicle_id 车辆编号
        * start_time 开始时间
        * end_time 开始时间
    '''
    # 时间参数是精确到day
    queryset = Vehicle.objects.all()
    serializer_class = VehicleLocationDetailSerializer
    lookup_field = 'vehicle_id'

    def get_object(self):
        vehicle_id = self.kwargs['vehicle_id']
        instance = Vehicle.objects.get(id=vehicle_id)
        return instance


class VehicleStatusUpdateViewSet(mixins.UpdateModelMixin,
                                 mixins.ListModelMixin,
                                 GenericViewSet):
    queryset = VehicleStatus.objects.all()
    serializer_class = VehicleStatusUpdateSerializer
    lookup_field = 'vehicle_id'
    pagination_class = None

    def get_object(self):
        vehicle_id = self.kwargs['vehicle_id']
        instance = VehicleStatus.objects.get(vehicle_id=vehicle_id)
        return instance

    def get_queryset(self):
        if self.action == "list":
            # 过滤出公司下的所有车辆
            company = self.request.user.company
            vehicle_ids = VehicleCompanyTerminal.objects.filter(company=company).values_list('vehicle_id', flat=True)
            return VehicleStatus.objects.filter(vehicle_id__in=vehicle_ids)
        return self.queryset

    def get_serializer_class(self):
        if self.action == "list":
            return VehicleStatusListSerializer
        return self.serializer_class


class VehicleAddressViewSet(mixins.RetrieveModelMixin, GenericViewSet):
    queryset = VehicleStatus.objects.all()
    serializer_class = VehicleAddressSerializer
    lookup_field = 'vehicle_id'

    def get_object(self):
        vehicle_id = self.kwargs['vehicle_id']
        instance = VehicleStatus.objects.get(vehicle_id=vehicle_id)
        return instance
